"use strict";

const fs = require("mz/fs");
const OSS = require("ali-oss");
const { Service } = require("egg");

class Oss extends Service {
    /**
     * 服务器简单上传服务
     * @param {File} file 上传的文件 (小于2M)
     * @param {string} dir 上传的文件夹 示例: /xxx
     * @param {string} url 上传的回调地址 示例: https://xxx.xxx.xxx/callback
     * @param {string} body 上传的回调参数 示例: bucket=${bucket}&object=${object}
     */
    async ossSimpleUploadService(file, dir, url, body) {
        const { ctx, config } = this;
        // xxxx.png => xxxx + .png
        const suffix = file.filename.slice(file.filename.lastIndexOf(".") - 1);
        // 1599884759597-ABCD{32}.png
        const fileName = `${Date.now()}-${ctx.helper.toMD5(file.filename)}${suffix}`;
        // 实例化OSS对象
        const client = new OSS({
            bucket: config.ossBucket,
            endpoint: config.ossEndpoint,
            accessKeyId: config.STS.accessKeyId,
            accessKeySecret: config.STS.accessKeySecret,
            cname: true,
            secure: true,
        });
        try {
            // 上传文件只能在线上测试
            const result = await client.put(`${dir}/${fileName}`, file.filepath, {
                callback: {
                    url,
                    body,
                },
            });
            return result;
        } finally {
            await fs.unlink(file.filepath);
        }
    }
    /**
     * 删除oss对象服务
     * @param {string} object 要删除的对象名
     */
    async ossDeleteService(object) {
        const { ctx, config } = this;
        // 实例化OSS对象
        const client = new OSS({
            bucket: config.ossBucket,
            region: config.ossRegion,
            accessKeyId: config.STS.accessKeyId,
            accessKeySecret: config.STS.accessKeySecret,
        });
        // 删除云存储的资源
        client.delete(object);
        // 删除数据库记录的资源-真实删除
        ctx.model.Resource.destroy({
            where: {
                path: object,
            },
            force: true,
        });
    }
    /**
     * 批量删除oss对象服务
     * @param {Array} objects oss对象名数组
     */
    async ossDeleteMultiService(objects) {
        const { ctx, config } = this;
        const client = new OSS({
            bucket: config.ossBucket,
            region: config.ossRegion,
            accessKeyId: config.STS.accessKeyId,
            accessKeySecret: config.STS.accessKeySecret,
        });
        // 删除云存储的资源
        client.deleteMulti(objects);
        // 删除数据库记录的资源-真实删除
        ctx.model.Resource.destroy({
            where: {
                path: objects,
            },
            force: true,
        });
    }
}

module.exports = Oss;
